import { DeleteOutlined, PlusOutlined, SettingOutlined } from "@ant-design/icons";
import { Collapse, Popconfirm, Space } from "antd";
import { ComponentConfig, ComponentSetter, useComponentConfigStore } from "@/stores/low-editor-comps-conf";
import type { ComponentEvent } from "@/stores/low-editor-comps-conf";
import { useComponentsStore } from "@/stores/edit-pages-store";
import { useState } from "react";
import { ActionModal, ActionConfig } from "./ActionModal";
import { AddEventButton } from "./AddEventButton";
import { ActionEcho } from "./ActionEcho";
import DndSortList from "@/components/DndSortList";
export function ComponentEvent() {
  const [actionModalOpen, setActionModalOpen] = useState(false);
  const [curEvent, setCurEvent] = useState<ComponentEvent>();
  const [curAction, setCurAction] = useState<ActionConfig>();
  const [curActionIndex, setCurActionIndex] = useState<number>();

  const { curComponent, curComponentId, updateComponentProps, removeComponentEvent } = useComponentsStore();
  const { flatComponentConfig } = useComponentConfigStore();
  const componentConfig = flatComponentConfig();

  if (!curComponent) return null;
  const allEvents = componentConfig?.[curComponent.name]?.events || [];
  if (allEvents.length === 0) return null;

  function editAction(config: ActionConfig, index: number, eventName: string) {
    const event = allEvents.find(item => item.name === eventName);
    !!event && setCurEvent(event);

    setCurAction(config);
    setCurActionIndex(index);

    setActionModalOpen(true);
  }
  function handleModalOk(config?: ActionConfig) {
    console.log("yeah", { config, curEvent,curAction });
    if (!config || !curEvent || !curComponent) {
      return;
    }

    if (curAction) {
      updateComponentProps(curComponent.id, {
        [curEvent.name]: {
          actions: curComponent.props[curEvent.name]?.actions.map((item: ActionConfig, index: number) => {
            return index === curActionIndex ? config : item;
          }),
        },
      });
    } else {
      updateComponentProps(curComponent.id, {
        [curEvent.name]: {
          actions: [...(curComponent.props[curEvent.name]?.actions || []), config],
        },
      });
    }
    setCurAction(undefined);
    setActionModalOpen(false);
  }
  const getExtra = (compEvent: ComponentEvent) => (
    <Space>
      <PlusOutlined
        onClick={event => {
          event.stopPropagation();
          setCurEvent(compEvent);
          setActionModalOpen(true);
        }}
      />
      <Popconfirm
        title="删除事件"
        description={`确认删除${compEvent.label}吗?`}
        onConfirm={event => {
          event?.stopPropagation();
          removeComponentEvent(curComponentId, compEvent.name);
        }}
        onCancel={event => {
          event?.stopPropagation();
        }}
      >
        <DeleteOutlined
          onClick={event => {
            event.stopPropagation();
          }}
        />
      </Popconfirm>
      {/* <SettingOutlined
        onClick={event => {
          event.stopPropagation();
        }}
      /> */}
    </Space>
  );
  const curComponentProps = curComponent?.props || {};
  const menuItems = allEvents
    .filter(event => Object.keys(curComponentProps).includes(event.name))
    .map(event => {
      return {
        key: event.name,
        label: event.label,
        extra: getExtra(event),
        children: (
          <DndSortList
            list={curComponent.props[event.name]?.actions || []}
            renderItem={ActionEcho}
            dragType={event.name}
            doAfterSort={arr => {
              updateComponentProps(curComponent.id, {
                [event.name]: { actions: arr },
              });
            }}
            cellExtraProps={{
              eventName: event.name,
              echoEditAction: editAction,
            }}
          />
        ),
      };
    });

  return (
    <div>
      <div className="m-3">
        <AddEventButton />
      </div>
      <Collapse
        ghost
        items={menuItems}
        expandIconPosition="end"
        className="classic headerGray contentNoPadding"
        defaultActiveKey={curComponent ? componentConfig[curComponent.name].events?.map(item => item.name) : []}
      />
      <ActionModal
        visible={actionModalOpen}
        handleCancel={() => setActionModalOpen(false)}
        handleOk={handleModalOk}
        action={curAction}
      />
    </div>
  );
}
